package com.yunban.project.template.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunban.project.template.mapper.PreviewRecordMapper;
import com.yunban.project.template.model.domain.PreviewRecord;
import com.yunban.project.template.model.dto.SavePreviewReq;
import com.yunban.project.template.service.PreviewRecordService;
import net.lab1024.sa.base.common.exception.BusinessException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;

/**
 * @author: lijiajun
 * @date: 2025-03-26
 * @version: 1.0
 */
@Service
public class PreviewRecordServiceImpl extends ServiceImpl<PreviewRecordMapper, PreviewRecord> implements PreviewRecordService {
    @Override
    public String savePreview(SavePreviewReq req) {
        PreviewRecord previewRecord = new PreviewRecord();
        previewRecord.setHtml(req.getHtml());
        // 过期时间30分钟
        previewRecord.setExpireTime(LocalDateTime.now().plusMinutes(30));
        this.save(previewRecord);
        return previewRecord.getPreviewId();
    }

    @Override
    public String getPreviewHtml(String previewId) {
        PreviewRecord previewRecord = this.getById(previewId);
        if (ObjectUtils.isEmpty(previewRecord)) {
            throw new BusinessException("记录不存在");
        }
        // 判断是否过期
        if (previewRecord.getExpireTime().isBefore(LocalDateTime.now())) {
            throw new BusinessException("记录已过期");
        }
        return previewRecord.getHtml();
    }

    public static void main(String[] args) {
        // 创建一个 LocalDateTime 对象 时间为 2025-03-27 12：00：00
        LocalDateTime localDateTime = LocalDateTime.of(2025, 3, 27, 18, 0, 0);
        System.out.println(localDateTime.isBefore(LocalDateTime.now()));
    }
}
